<?php
/**
 * CONTENIDO extension pack (mpContenidoX), consists of multiple classes to
 * provide more features for Plugins/Modules.
 *
 * @package     mpContenidoX
 * @subpackage  VariableStorage
 * @author      Murat Purc <murat@purc.de>
 * @copyright   Copyright (c) 2008-2012 Murat Purc (http://www.purc.de)
 * @license     http://www.gnu.org/licenses/gpl-2.0.html - GNU General Public License, version 2
 * @version     $Id: ContainerFile.class.php 21 2012-07-16 21:33:14Z purcaholic $
 */


defined('CON_FRAMEWORK') or die('Illegal call');


/**
 * mpVariableStorage_ContainerFile to store serialized configuration in files.
 *
 * Usage:
 * <code>
 * $options['key'] = '/full/path/to/config.php';
 *
 * $config = mpVariableStorage_Factory::get('filestorage', $options);
 * </code>
 *
 * @package     mpContenidoX
 * @subpackage  VariableStorage
 * @author      Murat Purc <murat@purc.de>
 */
class mpVariableStorage_ContainerFile extends mpVariableStorage_Abstract implements mpVariableStorage_Interface
{

    /**
     * Constructor of mpVariableStorage_ContainerFile, delegates parameter to parent.
     *
     * @param  array  $options  Assoziative options array as follows:
     * <code>
     * $options['key']      = Full path to configuration file
     * $options['lifetime'] = Lifetime of data in seconds, optional
     * </code>
     */
    public function __construct(array $options)
    {
        parent::__construct($options);

        if ($this->getExpires() && $this->exists() && filemtime($this->_key) < $this->getExpires()) {
            $this->remove();
        }
    }


    /**
     * Checks, if configuration file already exists.
     *
     * @return  bool
     */
    public function exists()
    {
        return (is_file($this->_key));
    }


    /**
     * Reads content of configuration file and returns the content as a unserialized PHP variable.
     *
     * @return  mixed  PHP variable or nul on error
     */
    public function get()
    {
        if (!is_file($this->_key)) {
            return null;
        }

        if ($content = file_get_contents($this->_key)) {
            return unserialize($content);
        } else {
            return null;
        }
    }


    /**
     * Serializes passed configuration and stores it into the configuation file
     *
     * @return  bool  True on success otherwhise false
     */
    public function set($content)
    {
        // use LOCK_EX if script is running under PHP5
        $flag = (defined('LOCK_EX')) ? LOCK_EX : null;
        $result = file_put_contents($this->_key, serialize($content), $flag);
        return ($result) ? true : false;
    }


    /**
     * Removes (unlink) configuration file.
     *
     * @return  bool  True on success otherwhise false
     */
    public function remove()
    {
        if (is_file($this->_key)) {
            return unlink($this->_key);
        }
        return false;
    }

}
